package com.xxx.rpc.common.util.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * 线程池
 * 
 * @author rosun
 *
 * ihavecar web server framework
 * WebSite: https://github.com/notyet/roscat
 * Licence: Apache v2 License
 */
public class ThreadPool {
	private ThreadPool(){
	}
	
	/**
	 * 所有BlockingQueue都可用于传输和保持提交的任务。可以使用此队列与池大小进行交互：
	 * 如果运行的线程少于corePoolSize，则Executor始终首选添加新的线程，而不进行排队。
	 * 如果运行的线程等于或多于corePoolSize，则Executor始终首选将请求加入队列，而不添加新的线程。
	 * 如果无法将请求加入队列，则创建新的线程，除非创建此线程超出maximumPoolSize，在这种情况下，任务将被拒绝（抛出RejectedExecutionException）。
	 * @return
	 */
	private static ThreadPoolExecutor createThreadPool(){
		int cpuCoreCount = Runtime.getRuntime().availableProcessors();
		ThreadPoolExecutor threadPoolInstance = new ThreadPoolExecutor(cpuCoreCount, cpuCoreCount*3, 
				2, TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(cpuCoreCount*10000));
		//设置allowCoreThreadTimeOut,允许回收超时的线程
		threadPoolInstance.allowCoreThreadTimeOut(true);
//		threadPoolInstance.setRejectedExecutionHandler(new RejectedExecutionHandler() {
//			@Override
//			public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
//				Logger.error(new Exception("RejectedExecution "));
//			}
//		});
		//Timer timer = new Timer("roscat@Thread_Pool_Timer");
//		ThreadPoolTask threadPoolTask = new ThreadPoolTask(threadPoolInstance,timer);
		//timer.schedule(threadPoolTask, 1, 1000);
		return threadPoolInstance;
	}
	
	public static ThreadPoolExecutor getNewThreadPool(){
		 return createThreadPool();	
	}
}
